/*
 * Copyright 2018 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.paboo.chart.decode;

import com.google.zxing.*;
import com.google.zxing.client.j2se.BufferedImageLuminanceSource;
import com.google.zxing.client.result.ResultParser;
import com.google.zxing.common.HybridBinarizer;
import com.google.zxing.multi.GenericMultipleBarcodeReader;
import com.google.zxing.multi.MultipleBarcodeReader;
import org.paboo.utils.LoggerFactoryUtils;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.util.*;

public class DecodeUtils {


    private static final int MAX_PIXELS = 1 << 25;
    private static final Map<DecodeHintType, Object> HINTS;
    private static final Map<DecodeHintType, Object> HINTS_PURE;
    private static LoggerFactoryUtils logger = LoggerFactoryUtils.getInstance().load(DecodeUtils.class);

    static {
        HINTS = new EnumMap<>(DecodeHintType.class);
        HINTS.put(DecodeHintType.CHARACTER_SET, StandardCharsets.UTF_8.name());
        HINTS.put(DecodeHintType.TRY_HARDER, Boolean.TRUE);
        HINTS.put(DecodeHintType.POSSIBLE_FORMATS, EnumSet.allOf(BarcodeFormat.class));
        HINTS_PURE = new EnumMap<>(HINTS);
        HINTS_PURE.put(DecodeHintType.PURE_BARCODE, Boolean.TRUE);
    }

    public static BufferedImage processStream(InputStream is) {
        BufferedImage image;
        try {
            image = ImageIO.read(is);
        } catch (IOException | IllegalArgumentException | ArrayIndexOutOfBoundsException e) {
            logger.info(e.toString());
            return null;
        }
        if (image == null) {
            return null;
        }

        int height = image.getHeight();
        int width = image.getWidth();
        if (height <= 1 || width <= 1 || height * width > MAX_PIXELS) {
            logger.info("Dimensions out of bounds: " + width + 'x' + height);
            return null;
        }
        return image;
    }

    public static ResponseJsonEntity processImage(BufferedImage image) {

        LuminanceSource source = new BufferedImageLuminanceSource(image);
        BinaryBitmap bitmap = new BinaryBitmap(new HybridBinarizer(source));
        ArrayList<Result> results = new ArrayList<>(1);

        try {
            Reader reader = new MultiFormatReader();
            ReaderException savedException = null;
            try {
                // Look for multiple barcodes
                MultipleBarcodeReader multiReader = new GenericMultipleBarcodeReader(reader);
                Result[] theResults = multiReader.decodeMultiple(bitmap, HINTS);
                if (theResults != null) {
                    results.addAll(Arrays.asList(theResults));
                }
                logger.info("Results：" + results.toString());
            } catch (ReaderException re) {
                savedException = re;
            }

            if (results.isEmpty()) {
                try {
                    // Look for pure barcode
                    Result theResult = reader.decode(bitmap, HINTS_PURE);
                    if (theResult != null) {
                        results.add(theResult);
                    }
                } catch (ReaderException re) {
                    savedException = re;
                }
            }

            if (results.isEmpty()) {
                try {
                    // Look for normal barcode in photo
                    Result theResult = reader.decode(bitmap, HINTS);
                    if (theResult != null) {
                        results.add(theResult);
                    }
                } catch (ReaderException re) {
                    savedException = re;
                }
            }

            if (results.isEmpty()) {
                try {
                    // Try again with other binarizer
                    BinaryBitmap hybridBitmap = new BinaryBitmap(new HybridBinarizer(source));
                    Result theResult = reader.decode(hybridBitmap, HINTS);
                    if (theResult != null) {
                        results.add(theResult);
                    }
                } catch (ReaderException re) {
                    savedException = re;
                }
            }

            if (results.isEmpty()) {
                logger.warn(savedException.getMessage(), savedException);
                return null;
            }

        } catch (RuntimeException re) {
            // Call out unexpected errors in the log clearly
            logger.warn("Unexpected exception from library", re);
            return null;
        }

        ResponseJsonEntity json = new ResponseJsonEntity();
        for (Result result : results) {
            if (result != null) {
                json.setRawtext(result.getText());
                json.setRawbytes(result.getRawBytes());
                json.setFormat(result.getBarcodeFormat().name());
                json.setParsedresult(ResultParser.parseResult(result).getDisplayResult());
            }
        }

        return json;
    }
}
